const User = require('../model/User');
const Advisor = require('../model/Advisor');
const Service = require('../model/Service')
const {getEnumKeyByValue, isValueInEnum} = require("../tool/function");
const {WORK_STATUS, SERVICE_STATUS, SERVICE_TYPE} = require("../model/other/enums");
const ApiError = require('../tool/utils/api_error')

/**
 * 顾问更改工作状态
 */
async function changeWorkStatus(advisorId, status) {
    if (!isValueInEnum(WORK_STATUS, status)) throw ApiError.BadRequest('工作状态值错误')
    const transaction = await User.sequelize.transaction();
    try {
        const advisor = await Advisor.findByPk(advisorId, {
            attributes: ['id', 'workStatus'],
        });

        if (!advisor) {
            throw ApiError.BadRequest('顾问不存在');
        }

        advisor.workStatus = status;
        await advisor.save({transaction});
        await transaction.commit();
    } catch (e) {
        await transaction.rollback()
        throw e
    }
}

/**
 * 顾问修改服务价格
 */
async function changeServicePrice(advisorId, serviceId, price) {
    const transaction = await User.sequelize.transaction();
    try {
        const service = await Service.findOne({
            where: {id: Number(serviceId), advisorId},
            attributes: ['id', 'price'],
        });

        if (!service) {
            throw ApiError.BadRequest('数据错误，该顾问下不存在这个服务');
        }

        service.price = parseFloat(price);
        await service.save({transaction});
        await transaction.commit();

    } catch (e) {
        await transaction.rollback();
        throw e; // 抛出给 route 层捕获
    }
}

/**
 * 顾问修改服务接单状态
 */
async function changeServiceStatus(advisorId, serviceStatus) {
    if(!isValueInEnum(SERVICE_STATUS, serviceStatus)) throw ApiError.BadRequest('服务状态的值错误');

    const transaction = await User.sequelize.transaction();
    try {
        const advisor = await Advisor.findByPk(Number(advisorId), {
            attributes: ['id', 'serviceStatus'],
            transaction
        });

        if (!advisor) {
            await transaction.rollback();
            throw ApiError.BadRequest('顾问不存在');
        }

        advisor.serviceStatus = Number(serviceStatus);
        await advisor.save({ transaction });
        await transaction.commit();
    } catch (e) {
        await transaction.rollback();
        throw e
    }
}

/**
 * 顾问新增服务
 */
async function createService(advisorId, serviceType, price, serviceName) {
    if(!isValueInEnum(SERVICE_TYPE, serviceType)) return { success: false, message: '服务类型错误' };
    //todo 检查价格

    const transaction = await User.sequelize.transaction();
    try {
        // 检查顾问是否存在
        const advisor = await Advisor.findByPk(Number(advisorId), { transaction });
        if (!advisor) {
            throw ApiError.BadRequest('顾问不存在');
        }

        const newService = await Service.create({
            advisorId,
            serviceType: Number(serviceType),
            price: parseFloat(price),
            serviceName
        }, { transaction });

        await transaction.commit();

        return newService
    } catch (err) {
        await transaction.rollback();
        console.error(err)
        throw err
    }
}

/**
 * 顾问信息详情（含服务列表）
 */
async function getAdvisorDetail(advisorId) {
    try {
        if (!advisorId) {
            throw ApiError.BadRequest('advisor_id 参数不能为空');
        }

        const advisor = await Advisor.findByPk(Number(advisorId), {
            attributes: { exclude: ['password'] },
            raw: true
        });

        if (!advisor) {
            throw ApiError.BadRequest('未找到对应顾问信息');
        }

        const services = await Service.findAll({
            where: { advisorId: Number(advisorId) },
            raw: true
        });

        return {advisor, services }
    } catch (err) {
        throw err
    }
}


module.exports = {
    changeWorkStatus,
    changeServicePrice,
    changeServiceStatus,
    createService,
    getAdvisorDetail
}
